import React, { useState, useEffect } from 'react';
import { getPricingRules, getActivePricingRule, createPricingRule, updatePricingRule, activatePricingRule } from '../services/api';

const Settings = () => {
  const [pricingRules, setPricingRules] = useState([]);
  const [, setActiveRule] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [formMode, setFormMode] = useState('add'); // 'add' 或 'edit'
  const [editingRule, setEditingRule] = useState(null);
  
  // 表单状态
  const [formData, setFormData] = useState({
    name: '',
    free_duration: 300, // 5分钟，单位秒
    unit_duration: 3600, // 1小时，单位秒
    unit_price: 5, // 5元
    is_active: false
  });

  const fetchData = async (showLoading = true) => {
    try {
      if (showLoading) {
        setLoading(true);
      }
      const [rulesResponse, activeRuleResponse] = await Promise.all([
        getPricingRules(),
        getActivePricingRule().catch(() => ({ data: null })) // 可能没有活跃规则
      ]);
      
      setPricingRules(rulesResponse.data);
      if (activeRuleResponse.data) {
        setActiveRule(activeRuleResponse.data);
      }
      if (showLoading) {
        setError(null);
      }
    } catch (err) {
      console.error('获取计费规则失败:', err);
      if (showLoading) {
        setError('获取计费规则失败，请稍后重试');
      }
    } finally {
      if (showLoading) {
        setLoading(false);
      }
    }
  };

  useEffect(() => {
    // 首次加载时显示loading
    fetchData(true);
    
    // 每5秒刷新一次数据，不显示loading
    const intervalId = setInterval(() => fetchData(false), 5000);
    return () => clearInterval(intervalId);
  }, []);

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    
    if (type === 'checkbox') {
      setFormData({ ...formData, [name]: checked });
    } else if (type === 'number') {
      setFormData({ ...formData, [name]: parseFloat(value) });
    } else {
      setFormData({ ...formData, [name]: value });
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    try {
      if (formMode === 'add') {
        await createPricingRule(formData);
      } else {
        await updatePricingRule(editingRule.id, formData);
      }
      
      // 重置表单
      setFormData({
        name: '',
        free_duration: 300,
        unit_duration: 3600,
        unit_price: 5,
        is_active: false
      });
      
      setFormMode('add');
      setEditingRule(null);
      
      // 刷新数据，不显示loading
      fetchData(false);
    } catch (err) {
      console.error('保存计费规则失败:', err);
      alert('保存计费规则失败，请稍后重试');
    }
  };

  const handleEdit = (rule) => {
    setFormMode('edit');
    setEditingRule(rule);
    setFormData({
      name: rule.name,
      free_duration: rule.free_duration,
      unit_duration: rule.unit_duration,
      unit_price: rule.unit_price,
      is_active: rule.is_active
    });
  };

  const handleActivate = async (ruleId) => {
    try {
      await activatePricingRule(ruleId);
      // 刷新数据，不显示loading
      fetchData(false);
    } catch (err) {
      console.error('激活计费规则失败:', err);
      alert('激活计费规则失败，请稍后重试');
    }
  };

  const formatDuration = (seconds) => {
    if (seconds < 60) {
      return `${seconds}秒`;
    } else if (seconds < 3600) {
      return `${Math.floor(seconds / 60)}分钟`;
    } else {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      return `${hours}小时${minutes > 0 ? ` ${minutes}分钟` : ''}`;
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
          <p>{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold text-gray-800">系统设置</h1>
      </div>
      
      <div className="bg-white rounded-lg shadow-md p-6">
        <h2 className="text-lg font-semibold text-gray-800 mb-4">计费规则管理</h2>
        
        <form onSubmit={handleSubmit} className="space-y-4 mb-8">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              规则名称
            </label>
            <input
              type="text"
              name="name"
              value={formData.name}
              onChange={handleInputChange}
              className="w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="例如：工作日规则"
              required
            />
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                免费时长 (秒)
              </label>
              <input
                type="number"
                name="free_duration"
                value={formData.free_duration}
                onChange={handleInputChange}
                className="w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                min="0"
                required
              />
              <p className="text-sm text-gray-500 mt-1">
                {formatDuration(formData.free_duration)}
              </p>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                计费单位时长 (秒)
              </label>
              <input
                type="number"
                name="unit_duration"
                value={formData.unit_duration}
                onChange={handleInputChange}
                className="w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                min="1"
                required
              />
              <p className="text-sm text-gray-500 mt-1">
                {formatDuration(formData.unit_duration)}
              </p>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                单位价格 (元)
              </label>
              <input
                type="number"
                name="unit_price"
                value={formData.unit_price}
                onChange={handleInputChange}
                className="w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                min="0"
                step="0.01"
                required
              />
            </div>
          </div>
          
          <div className="flex items-center">
            <input
              type="checkbox"
              name="is_active"
              checked={formData.is_active}
              onChange={handleInputChange}
              className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            />
            <label className="ml-2 block text-sm text-gray-900">
              设为活跃规则
            </label>
          </div>
          
          <div className="flex justify-end space-x-2">
            {formMode === 'edit' && (
              <button
                type="button"
                onClick={() => {
                  setFormMode('add');
                  setEditingRule(null);
                  setFormData({
                    name: '',
                    free_duration: 300,
                    unit_duration: 3600,
                    unit_price: 5,
                    is_active: false
                  });
                }}
                className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
              >
                取消
              </button>
            )}
            <button
              type="submit"
              className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700"
            >
              {formMode === 'add' ? '添加规则' : '保存修改'}
            </button>
          </div>
        </form>
        
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  名称
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  免费时长
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  计费单位
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  单位价格 (元)
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  状态
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {pricingRules.map((rule) => (
                <tr key={rule.id}>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    {rule.name}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {formatDuration(rule.free_duration)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {formatDuration(rule.unit_duration)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {rule.unit_price.toFixed(2)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    {rule.is_active ? (
                      <span className="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">
                        活跃
                      </span>
                    ) : (
                      <span className="px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800">
                        未激活
                      </span>
                    )}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    <div className="flex space-x-2">
                      <button
                        onClick={() => handleEdit(rule)}
                        className="text-blue-600 hover:text-blue-900"
                      >
                        编辑
                      </button>
                      {!rule.is_active && (
                        <button
                          onClick={() => handleActivate(rule.id)}
                          className="text-green-600 hover:text-green-900"
                        >
                          激活
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          
          {pricingRules.length === 0 && (
            <p className="text-gray-500 text-center py-4">暂无计费规则</p>
          )}
        </div>
      </div>
    </div>
  );
};

export default Settings; 